package server.controller;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
import java.util.Collection;

import javax.vecmath.Quat4d;
import javax.vecmath.Vector3d;

import server.BroadcastUpdates;
import server.model.Object3D;

public class Universe3DControllerImpl extends UnicastRemoteObject implements Universe3DControllerRemoteInterface {

	private static final long serialVersionUID = -466023117486887843L;
	private Collection<ServerObject3DController> objectControllers;
	private int nbObjects;
	private int nbClients;
	
	// Constructors
	public Universe3DControllerImpl() throws RemoteException {
		System.out.println("Bigbang!");
		objectControllers = new ArrayList<ServerObject3DController>();
		nbObjects = 0;
		nbClients = 0;
	}
	
	// Universe3DControllerInterface Methods
	public String getUniverseName() throws RemoteException {
		return "Univers 1";
	}
	
	public String newClientName() throws RemoteException{
		nbClients++;
		return "Client"+nbClients;
	}

	public void addViewpoint3DController(String name, Vector3d position, Quat4d orientation, String file) throws RemoteException {
		nbObjects++;
		Object3D oTemp = new Object3D(name,position,orientation,file);
		ServerObject3DController cTemp = new ServerObject3DControllerImpl(oTemp);
		objectControllers.add(cTemp);
		BroadcastUpdates.getSharedInstance().diffuseMessage(cTemp.getName(), cTemp.getPosition(), cTemp.getOrientation(), cTemp.getFileLoaded());
	}
	
	public void addObject3DController(String name, Vector3d position, Quat4d orientation, String file) throws RemoteException {
		nbObjects++;
		Object3D oTemp = new Object3D(name+nbObjects,position,orientation,file);
		ServerObject3DController cTemp = new ServerObject3DControllerImpl(oTemp);
		objectControllers.add(cTemp);
		System.out.println("Creation de l'objet: "+oTemp.getName());
		BroadcastUpdates.getSharedInstance().diffuseMessage(cTemp.getName(), cTemp.getPosition(), cTemp.getOrientation(), cTemp.getFileLoaded());
	}

	public Collection<String> getAllObjectsController() throws RemoteException {
		Collection<String> controllersName = new ArrayList<String>();
		for (ServerObject3DController c : objectControllers) {
			controllersName.add(c.getName());
		}
		return controllersName;
	}

	public ServerObject3DController getObjectControllerByName(String name) throws RemoteException {
		ServerObject3DController result = null;
		for (ServerObject3DController c : objectControllers) {
			if (c.getName().equals(name)) {
				result = c;
			}
		}
		return result;
	}

}
